<template>
  <div class="files-page">
    <div class="page-header">
      <h1>文件管理</h1>
      <div class="header-actions">
        <el-upload
          action="/api/files/single"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
        >
          <el-button type="primary">
            <el-icon><UploadFilled /></el-icon>
            上传文件
          </el-button>
        </el-upload>
        <el-upload
          action="/api/files/multiple"
          :auto-upload="false"
          :show-file-list="false"
          :on-change="handleFilesChange"
          :before-upload="beforeUpload"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          multiple
        >
          <el-button type="primary" plain>
            <el-icon><UploadFilled /></el-icon>
            批量上传
          </el-button>
        </el-upload>
      </div>
    </div>

    <el-tabs v-model="activeTab" @tab-click="handleTabChange">
      <el-tab-pane label="图片文件" name="images">
        <div class="file-grid">
          <div
            v-for="file in imageFiles"
            :key="file.filename"
            class="file-item"
          >
            <div class="file-preview">
              <img :src="file.url" :alt="file.filename" />
              <div class="file-overlay">
                <el-button-group>
                  <el-button type="primary" size="small" @click="copyFileUrl(file)">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                  <el-button type="danger" size="small" @click="handleDelete(file)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </div>
            </div>
            <div class="file-info">
              <p class="file-name" :title="file.filename">{{ file.filename }}</p>
              <p class="file-size">{{ formatFileSize(file.size) }}</p>
              <p class="file-time">{{ formatDate(file.created) }}</p>
            </div>
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="文档文件" name="documents">
        <el-table :data="documentFiles" v-loading="loading">
          <el-table-column prop="filename" label="文件名" min-width="200">
            <template #default="{ row }">
              <div class="file-name-cell">
                <el-icon><Document /></el-icon>
                <span :title="row.filename">{{ row.filename }}</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="size" label="大小" width="120">
            <template #default="{ row }">
              {{ formatFileSize(row.size) }}
            </template>
          </el-table-column>
          <el-table-column prop="created" label="上传时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button-group>
                <el-button type="primary" size="small" @click="copyFileUrl(row)">
                  <el-icon><CopyDocument /></el-icon>
                  复制链接
                </el-button>
                <el-button type="primary" size="small" @click="downloadFile(row)">
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button type="danger" size="small" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </el-button-group>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>

    <!-- 删除确认对话框 -->
    <el-dialog
      v-model="deleteDialogVisible"
      title="确认删除"
      width="30%"
    >
      <span>确定要删除文件 "{{ selectedFile?.filename }}" 吗？</span>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { UploadFilled, CopyDocument, Delete, Document, Download } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import dayjs from 'dayjs'
import { config, apiEndpoints } from '@/config'

// 配置 axios 默认值
axios.defaults.baseURL = config.apiBaseUrl

interface FileInfo {
  filename: string
  size: number
  created: string
  modified: string
  url: string
  type: 'images' | 'documents'
}

const activeTab = ref('images')
const loading = ref(false)
const imageFiles = ref<FileInfo[]>([])
const documentFiles = ref<FileInfo[]>([])
const deleteDialogVisible = ref(false)
const selectedFile = ref<FileInfo | null>(null)

// 获取文件列表
const fetchFiles = async (type: 'images' | 'documents') => {
  loading.value = true
  try {
    const response = await axios.get(apiEndpoints.files.list(type))
    if (type === 'images') {
      imageFiles.value = response.data.data
    } else {
      documentFiles.value = response.data.data
    }
  } catch (error) {
    ElMessage.error('获取文件列表失败')
    console.error('获取文件列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 处理标签页切换
const handleTabChange = () => {
  fetchFiles(activeTab.value as 'images' | 'documents')
}

// 文件上传前的验证
const beforeUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isDocument = /\.(pdf|doc|docx|txt|md)$/i.test(file.name)
  
  if (!isImage && !isDocument) {
    ElMessage.error('不支持的文件类型')
    return false
  }
  
  const maxSize = 5 * 1024 * 1024 // 5MB
  if (file.size > maxSize) {
    ElMessage.error('文件大小不能超过 5MB')
    return false
  }
  
  return true
}

// 处理单文件上传
const handleFileChange = (file: any) => {
  if (file) {
    const formData = new FormData()
    formData.append('file', file.raw)
    
    axios.post(apiEndpoints.files.single, formData)
      .then(response => {
        ElMessage.success('文件上传成功')
        fetchFiles(activeTab.value as 'images' | 'documents')
      })
      .catch(error => {
        ElMessage.error(error.response?.data?.error || '文件上传失败')
      })
  }
}

// 处理多文件上传
const handleFilesChange = (files: any) => {
  if (files.length > 0) {
    const formData = new FormData()
    files.forEach((file: any) => {
      formData.append('files', file.raw)
    })
    
    axios.post(apiEndpoints.files.multiple, formData)
      .then(response => {
        ElMessage.success(`成功上传 ${response.data.count} 个文件`)
        fetchFiles(activeTab.value as 'images' | 'documents')
      })
      .catch(error => {
        ElMessage.error(error.response?.data?.error || '文件上传失败')
      })
  }
}

// 处理上传成功
const handleUploadSuccess = (response: any) => {
  ElMessage.success('文件上传成功')
  fetchFiles(activeTab.value as 'images' | 'documents')
}

// 处理上传失败
const handleUploadError = (error: any) => {
  ElMessage.error(error.response?.data?.error || '文件上传失败')
}

// 复制文件链接
const copyFileUrl = async (file: FileInfo) => {
  try {
    await navigator.clipboard.writeText(file.url)
    ElMessage.success('文件链接已复制到剪贴板')
  } catch (error) {
    ElMessage.error('复制链接失败')
  }
}

// 下载文件
const downloadFile = (file: FileInfo) => {
  const link = document.createElement('a')
  link.href = file.url
  link.download = file.filename
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 处理删除
const handleDelete = (file: FileInfo) => {
  selectedFile.value = file
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  if (!selectedFile.value) return
  
  try {
    const fileType = selectedFile.value.type || (selectedFile.value.url.includes('/images/') ? 'images' : 'documents')
    
    await axios.delete(apiEndpoints.files.delete(fileType, selectedFile.value.filename))
    ElMessage.success('文件删除成功')
    deleteDialogVisible.value = false
    fetchFiles(activeTab.value as 'images' | 'documents')
  } catch (error: any) {
    console.error('删除文件失败:', error)
    ElMessage.error(error.response?.data?.error || '文件删除失败')
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 初始化
onMounted(() => {
  fetchFiles(activeTab.value as 'images' | 'documents')
})
</script>

<style scoped>
.files-page {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 12px;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.file-item {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
}

.file-item:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.file-preview {
  position: relative;
  width: 100%;
  height: 150px;
  overflow: hidden;
}

.file-preview img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.file-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.file-preview:hover .file-overlay {
  opacity: 1;
}

.file-info {
  padding: 12px;
}

.file-name {
  margin: 0;
  font-size: 14px;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.file-size, .file-time {
  margin: 4px 0 0;
  font-size: 12px;
  color: #909399;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name-cell .el-icon {
  font-size: 16px;
  color: #909399;
}

:deep(.el-upload) {
  width: auto;
}

:deep(.el-button-group) {
  display: flex;
  gap: 4px;
}

:deep(.el-button-group .el-button) {
  margin-left: 0 !important;
}
</style> 